﻿/*
Copyright (c) 2011, Pawel Szczurek
All rights reserved.


Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:


Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without
specific prior written permission.


THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Alice.VM;

namespace Alice.Compiler
{
    internal class VariableManager
    {
        class Scope
        {
            internal Scope(bool allowLookUp, int beginOffset)
            {
                AllowLookUp = allowLookUp;
                BeginOffset = beginOffset;
            }
            internal Dictionary<string, int> Offset = new Dictionary<string,int>();
            internal readonly bool AllowLookUp;
            internal readonly int BeginOffset;
        }

        internal VariableManager(CodeGenerator owner)
        {
            m_owner = owner;
        }

        internal void BeginScope(bool separated)
        {
            m_scopes.Add(new Scope(!separated, m_owner.RuntimeStackTop()));
        }

        internal void EndScope(bool returnValueOnStack)
        {
            Scope s = m_scopes[m_scopes.Count - 1];
            m_scopes.RemoveAt(m_scopes.Count - 1);

            Debug.Assert(s.BeginOffset + s.Offset.Count + (returnValueOnStack ? 1 : 0) == m_owner.RuntimeStackTop());

            //pop all values from stack
           // m_owner.Pop(s.Offset.Count);
        }

        public void DefineVar(string name)
        {
            SetVariableOffset(name);

            //load var name
          //  m_owner.LoadConst(name);

            //define var
          //  m_owner.EmitOpCode(OPCodes.DefineStackVar, 0);
        }

        /// <summary>
        /// stack +1
        /// </summary>
        /// <param name="name"></param>
        public void LoadVar(string name)
        {
            /*//create const with name
            m_owner.LoadConst(name);

            //load var
            m_owner.m_program.Add((byte)OPCodes.LoadNamedVar);
            //ChangeRuntimeStack(+0);*/

            int offset = GetVariableOffset(name);
            m_owner.LoadArg(offset);
            m_owner.EmitOpCode(OPCodes.GetStackVar, 0);
        }

        /// <summary>
        /// stack -1
        /// </summary>
        /// <param name="name"></param>
        public void StoreVar(string name)
        {
            /*//create const with name
            m_owner.LoadConst(name);

            //load var
            m_owner.m_program.Add((byte)OPCodes.StoreNamedVar);
            m_owner.ChangeRuntimeStack(-2);*/

            int offset = GetVariableOffset(name);
            m_owner.LoadArg(offset - 1);        //-1 because there is value on stack that will be pop'ed before set stack var
            m_owner.EmitOpCode(OPCodes.SetStackVar, -1);
        }

        public int ScopesCount
        {
            get { return m_scopes.Count; }
        }

        #region private

        void SetVariableOffset(string name)
        {
            int currentId = m_scopes.Count - 1;

            //check if not exist
            while(true)
            {
                if (m_scopes[currentId].Offset.ContainsKey(name))
                {
                    Debug.Assert(false, "name already in use");
                    throw new Exception("name already in use");
                }

                if (m_scopes[currentId].AllowLookUp)
                    currentId--;
                else
                    break;
            }

            //add
            m_scopes[m_scopes.Count - 1].Offset.Add(name, m_owner.RuntimeStackTop());
        }
        int GetVariableOffset(string name)
        {
            int currentId = m_scopes.Count - 1;

            //check if not exist
            while (true)
            {
                if (m_scopes[currentId].Offset.ContainsKey(name))
                {
                    Debug.Assert(m_owner.RuntimeStackTop() - m_scopes[currentId].Offset[name] >= 0);
                    return m_owner.RuntimeStackTop() - m_scopes[currentId].Offset[name];
                }

                if (m_scopes[currentId].AllowLookUp)
                    currentId--;
                else
                {
                    Debug.Assert(false, "error name undefined");
                    throw new Exception("error name undefined");
                }
            }
        }

        readonly CodeGenerator m_owner;
        int m_stackTop = 0;
        List<Scope> m_scopes = new List<Scope>();

        #endregion
    }
}
